package com.chatplus.application.processor;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.processor.constant.AIConstants;
import com.chatplus.application.processor.handler.ChatAiUtilHandler;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Objects;

/**
 * 流监听器
 */
public abstract class StreamEventSourceListener extends EventSourceListener {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(StreamEventSourceListener.class);

    protected final ChatAiUtilHandler chatAiUtilHandler;

    protected StreamEventSourceListener(WebSocketSession session, String platform, String prompt) {
        chatAiUtilHandler = new ChatAiUtilHandler(session, platform, prompt);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        LOGGER.message("连接成功").context("eventSource", eventSource.request()).context("response", response).info();
        chatAiUtilHandler.sendMessage(AIConstants.START_LABEL);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) {
        chatAiUtilHandler.replyErrorMessage("模型不存在或者已禁用");
    }

    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        LOGGER.message("关闭连接").info();
    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, Throwable t, Response response) {
        if (Objects.isNull(response)) {
            return;
        }
        try {
            ResponseBody body = response.body();
            if (Objects.nonNull(body)) {
                String bodyStr = body.string();
                LOGGER.message("连接异常").context("data", bodyStr).exception(t).error();
                chatAiUtilHandler.replyErrorMessage("服务端发生异常，等待管理员修复,第三方返回: " + bodyStr);

            } else {
                LOGGER.message("连接异常").context("data", response).exception(t).error();
                chatAiUtilHandler.replyErrorMessage("服务端发生异常，等待管理员修复!");
            }
        } catch (IOException e) {
            LOGGER.message("连接异常").exception(e).error();
        }
        eventSource.cancel();
    }

}
